<script lang="ts" setup>
import { ArrowDown, ArrowRight, Refresh, Search } from "@element-plus/icons-vue"
import { computed, reactive, ref, watch } from "vue"
import { useChartStore } from "../../pinia/stores/chartStore"
import MatchDetail from "./components/MatchDetail.vue"
import type * as Football from "./apis/type"

defineOptions({
  name: "FootballChart"
})

// 标签页状态
const activeTab = ref("current-match")

// 第一个标签页状态
const searchFormRef = ref()
const searchData = reactive({
  createTime: "",
  league: "",
  eventName: ""
})
const isSearchFormExpanded = ref(true)

// 第二个标签页状态
const similarSearchData = reactive({
  eventName: "",
  williamWin: [1.9, 2.0] as [number | null, number | null],
  williamDraw: [2.0, 4.0] as [number | null, number | null],
  williamLose: [3.0, 4.0] as [number | null, number | null],
  signalWin: [1.9, 2.0] as [number | null, number | null],
  signalDraw: [1.8083, 2.0984] as [number | null, number | null],
  signalLose: [1.5420, 1.7801] as [number | null, number | null]
})
const expandedRows = ref<Set<number>>(new Set())

function toggleSearchForm() {
  isSearchFormExpanded.value = !isSearchFormExpanded.value
}

function handleEventDropdownVisible(visible: boolean) {
  if (visible && chartStore.eventOptions.length === 0) {
    chartStore.fetchEventList()
  }
}

function handleSearch() {
  if (searchData.createTime && searchData.createTime.length === 2) {
    const dateRange = {
      start: searchData.createTime[0],
      end: searchData.createTime[1]
    }
    chartStore.fetchLeaguesByDateRange(dateRange, searchData.eventName || undefined)
  }
}

function resetSearch() {
  searchFormRef.value?.resetFields()
  chartStore.resetAllData()
}

function handleSimilarSearch(page: number = 1) {
  // 构建搜索条件，确保数值类型正确
  const condition: Football.SimilarMatchesCondition = {
    event_name: similarSearchData.eventName || undefined,
    home_initial_min: parseFloat(similarSearchData.williamWin[0] as string) || 0,
    home_initial_max: parseFloat(similarSearchData.williamWin[1] as string) || 999,
    draw_initial_min: parseFloat(similarSearchData.williamDraw[0] as string) || 0,
    draw_initial_max: parseFloat(similarSearchData.williamDraw[1] as string) || 999,
    away_initial_min: parseFloat(similarSearchData.williamLose[0] as string) || 0,
    away_initial_max: parseFloat(similarSearchData.williamLose[1] as string) || 999,
    signal_home_initial_min: parseFloat(similarSearchData.signalWin[0] as string) || -999,
    signal_home_initial_max: parseFloat(similarSearchData.signalWin[1] as string) || 999,
    signal_draw_initial_min: parseFloat(similarSearchData.signalDraw[0] as string) || -999,
    signal_draw_initial_max: parseFloat(similarSearchData.signalDraw[1] as string) || 999,
    signal_away_initial_min: parseFloat(similarSearchData.signalLose[0] as string) || -999,
    signal_away_initial_max: parseFloat(similarSearchData.signalLose[1] as string) || 999,
    current_page: page,
    page_size: 20
  }
  
  console.log("构建的搜索条件:", condition)
  chartStore.fetchSimilarMatches(condition)
}

function handlePageChange(page: number) {
  handleSimilarSearch(page)
}

function resetSimilarSearch() {
  similarSearchData.eventName = ""
  similarSearchData.williamWin = [1.9, 2.0]
  similarSearchData.williamDraw = [2.0, 4.0]
  similarSearchData.williamLose = [3.0, 4.0]
  similarSearchData.signalWin = [1.9, 2.0]
  similarSearchData.signalDraw = [1.8083, 2.0984]
  similarSearchData.signalLose = [1.5420, 1.7801]
  expandedRows.value.clear()
  // 重置分页到第一页
  chartStore.similarMatchesPagination.current_page = 1
}

function handleSimilarMatchDetail(match: Football.SimilarMatches) {
  if (expandedRows.value.has(match.fid!)) {
    expandedRows.value.delete(match.fid!)
  } else {
    expandedRows.value.add(match.fid!)
    chartStore.selectSimilarMatch(match)
  }
}

const chartStore = useChartStore()

// 监听赛事名称变化，自动应用筛选
watch(() => searchData.eventName, (newEventName) => {
  chartStore.selectedEvent = newEventName
  // 当赛事名称改变时，自动触发查询
  if (newEventName && searchData.createTime && searchData.createTime.length === 2) {
    const dateRange = {
      start: searchData.createTime[0],
      end: searchData.createTime[1]
    }
    chartStore.fetchLeaguesByDateRange(dateRange, newEventName)
  }
})

watch(() => searchData.league, (newLeagueId) => {
  if (newLeagueId) chartStore.selectLeague(newLeagueId)
})

// 监听标签页切换，自动设置相似比赛的区间
watch(activeTab, (newTab) => {
  if (newTab === 'similar-match') {
    updateSimilarSearchRanges()
  }
})

// 监听当前选择的比赛变化，更新相似比赛区间
watch(() => chartStore.selectedLeague, () => {
  if (activeTab.value === 'similar-match') {
    updateSimilarSearchRanges()
  }
})

// 根据当前选择的比赛更新相似搜索区间
function updateSimilarSearchRanges() {
  const leftTableData = chartStore.leftTableData
  
  if (leftTableData && leftTableData.length > 0) {
    // 获取第一行数据（初赔）
    const firstRow = leftTableData[0]
    
    // 威廉希尔初赔区间 ±0.2
    similarSearchData.williamWin = [
      Number((firstRow.homeWin - 0.2).toFixed(2)),
      Number((firstRow.homeWin + 0.2).toFixed(2))
    ]
    similarSearchData.williamDraw = [
      Number((firstRow.draw - 0.2).toFixed(2)),
      Number((firstRow.draw + 0.2).toFixed(2))
    ]
    similarSearchData.williamLose = [
      Number((firstRow.awayWin - 0.2).toFixed(2)),
      Number((firstRow.awayWin + 0.2).toFixed(2))
    ]
    
    // 信号值区间 ±0.2
    if (firstRow.signalHome !== null) {
      similarSearchData.signalWin = [
        Number((firstRow.signalHome - 0.05).toFixed(4)),
        Number((firstRow.signalHome + 0.05).toFixed(4))
      ]
    }
    if (firstRow.signalDraw !== null) {
      similarSearchData.signalDraw = [
        Number((firstRow.signalDraw - 0.05).toFixed(4)),
        Number((firstRow.signalDraw + 0.05).toFixed(4))
      ]
    }
    if (firstRow.signalAway !== null) {
      similarSearchData.signalLose = [
        Number((firstRow.signalAway - 0.05).toFixed(4)),
        Number((firstRow.signalAway + 0.05).toFixed(4))
      ]
    }
    
    console.log('根据当前比赛更新相似搜索区间:', {
      williamWin: similarSearchData.williamWin,
      williamDraw: similarSearchData.williamDraw,
      williamLose: similarSearchData.williamLose,
      signalWin: similarSearchData.signalWin,
      signalDraw: similarSearchData.signalDraw,
      signalLose: similarSearchData.signalLose
    })
  }
}

// 组件挂载时获取赛事列表
import { onMounted } from "vue"

onMounted(() => {
  chartStore.fetchEventList()
})


// Chart data configurations
const chartData293 = computed(() => ({
  xData: chartStore.leftBottomChart293?.xData || [],
  seriesData: chartStore.leftBottomChart293?.seriesData || []
}))

const chartData18 = computed(() => ({
  xData: chartStore.leftBottomChart18?.xData || [],
  seriesData: chartStore.leftBottomChart18?.seriesData || []
}))

const chartDataCombinedHome = computed(() => ({
  xData: chartStore.rightCombinedChartHome?.xData || [],
  seriesData: chartStore.rightCombinedChartHome?.seriesData || []
}))

const chartDataCombinedDraw = computed(() => ({
  xData: chartStore.rightCombinedChartDraw?.xData || [],
  seriesData: chartStore.rightCombinedChartDraw?.seriesData || []
}))

const chartDataCombinedAway = computed(() => ({
  xData: chartStore.rightCombinedChartAway?.xData || [],
  seriesData: chartStore.rightCombinedChartAway?.seriesData || []
}))

// 相似比赛图表数据
const similarMatchChartData293 = computed(() => ({
  xData: chartStore.similarMatchLeftBottomChart293?.xData || [],
  seriesData: chartStore.similarMatchLeftBottomChart293?.seriesData || []
}))

const similarMatchChartData18 = computed(() => ({
  xData: chartStore.similarMatchLeftBottomChart18?.xData || [],
  seriesData: chartStore.similarMatchLeftBottomChart18?.seriesData || []
}))

const similarMatchChartDataCombinedHome = computed(() => ({
  xData: chartStore.similarMatchRightCombinedChartHome?.xData || [],
  seriesData: chartStore.similarMatchRightCombinedChartHome?.seriesData || []
}))

const similarMatchChartDataCombinedDraw = computed(() => ({
  xData: chartStore.similarMatchRightCombinedChartDraw?.xData || [],
  seriesData: chartStore.similarMatchRightCombinedChartDraw?.seriesData || []
}))

const similarMatchChartDataCombinedAway = computed(() => ({
  xData: chartStore.similarMatchRightCombinedChartAway?.xData || [],
  seriesData: chartStore.similarMatchRightCombinedChartAway?.seriesData || []
}))

// 获取指定比赛的图表数据
function getMatchChartData(fid: number) {
  const matchData = chartStore.similarMatchDataMap.get(fid)
  if (!matchData) {
    return null
  }
  
  return {
    leftTableData: matchData.leftTableData,
    rightTableData: matchData.rightTableData,
    similarMatchChartData293: matchData.leftBottomChart293,
    similarMatchChartData18: matchData.leftBottomChart18,
    similarMatchChartDataCombinedHome: matchData.rightCombinedChartHome,
    similarMatchChartDataCombinedDraw: matchData.rightCombinedChartDraw,
    similarMatchChartDataCombinedAway: matchData.rightCombinedChartAway,
    isLoading: matchData.isLoading
  }
}
</script>

<template>
  <div class="app-container h-screen flex flex-col">
    <!-- 标签页导航 -->
    <el-tabs v-model="activeTab" type="card" class="flex-1">
      <el-tab-pane label="当前比赛" name="current-match">
        <!-- 第一个标签页内容 -->
        <el-card v-loading="chartStore.isLoadingLeagues" shadow="never" class="mt-1 mb-1">
          <div class="flex justify-between">
            <span class="text-sm font-bold">搜索条件</span>
            <el-button
              :icon="isSearchFormExpanded ? ArrowDown : ArrowRight"
              @click="toggleSearchForm"
              type="text"
            >
              {{ isSearchFormExpanded ? '收起' : '展开' }}
            </el-button>
          </div>

          <el-form
            ref="searchFormRef"
            :inline="true"
            :model="searchData"
            v-show="isSearchFormExpanded"
          >
            <el-form-item prop="eventName" label="赛事名称">
              <el-select
                v-model="searchData.eventName"
                placeholder="请选择赛事名称"
                clearable
                style="width: 200px;"
                @visible-change="handleEventDropdownVisible"
              >
                <el-option
                  v-for="item in chartStore.eventOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="league" label="联赛">
              <el-select
                v-model="searchData.league"
                placeholder="请选择联赛"
                popper-class="league-select-popper"
                style="width: fit-content; min-width: 450px;"
              >
                <el-option
                  v-for="item in chartStore.leagueOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="createTime" label="比赛时间">
              <el-date-picker
                v-model="searchData.createTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">
                查询
              </el-button>
              <el-button :icon="Refresh" @click="resetSearch">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 内容展示区域 -->
        <div class="flex-1 overflow-auto">
          <MatchDetail
            :isLoadingSignals="chartStore.isLoadingSignals"
            :leftTableData="chartStore.leftTableData"
            :rightTableData="chartStore.rightTableData"
            :chartData293="chartData293"
            :chartData18="chartData18"
            :chartDataCombinedHome="chartDataCombinedHome"
            :chartDataCombinedDraw="chartDataCombinedDraw"
            :chartDataCombinedAway="chartDataCombinedAway"
          />
        </div>
      </el-tab-pane>

      <!-- 第二个标签页：相似比赛 -->
       <el-tab-pane label="相似比赛" name="similar-match" >
    
      <!-- 搜索条件 Card -->
      <el-card shadow="never" class="flex-shrink-0">
        <!-- 搜索表单内容 (保持不变) -->
        <div class="flex">
          <div class="flex-1">
            <div class="flex justify-between">
              <span class="text-sm font-bold">搜索条件</span>
            </div>
            <el-form :inline="true" :model="similarSearchData">
              <!-- 表单内容 (保持不变) -->
              <div class="flex flex-col space-y-1">
                <div>
                  <el-form-item prop="eventName" label="赛事名称">
                    <el-select
                      v-model="similarSearchData.eventName"
                      placeholder="请选择赛事名称"
                      clearable
                      style="width: 200px;"
                      @visible-change="handleEventDropdownVisible"
                    >
                      <el-option
                        v-for="item in chartStore.eventOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </div>
                <div>
                  <el-form-item label="威廉希尔初赔区间">
                    <div class="flex items-center gap-1">
                      <span>胜:</span>
                      <el-input v-model="similarSearchData.williamWin[0]" placeholder="最小值" style="width: 80px;" />
                      <span>-</span>
                      <el-input v-model="similarSearchData.williamWin[1]" placeholder="最大值" style="width: 80px;" />
                      <span class="ml-2">平:</span>
                      <el-input v-model="similarSearchData.williamDraw[0]" placeholder="最小值" style="width: 80px;" />
                      <span>-</span>
                      <el-input v-model="similarSearchData.williamDraw[1]" placeholder="最大值" style="width: 80px;" />
                      <span class="ml-2">负:</span>
                      <el-input v-model="similarSearchData.williamLose[0]" placeholder="最小值" style="width: 80px;" />
                      <span>-</span>
                      <el-input v-model="similarSearchData.williamLose[1]" placeholder="最大值" style="width: 80px;" />
                    </div>
                  </el-form-item>
                </div>
                <div>
                  <el-form-item label="威廉希尔初赔信号值">
                    <div class="flex items-center gap-1">
                      <span>胜:</span>
                      <el-input v-model="similarSearchData.signalWin[0]" placeholder="最小值" style="width: 80px;" />
                      <span>-</span>
                      <el-input v-model="similarSearchData.signalWin[1]" placeholder="最大值" style="width: 80px;" />
                      <span class="ml-2">平:</span>
                      <el-input v-model="similarSearchData.signalDraw[0]" placeholder="最小值" style="width: 80px;" />
                      <span>-</span>
                      <el-input v-model="similarSearchData.signalDraw[1]" placeholder="最大值" style="width: 80px;" />
                      <span class="ml-2">负:</span>
                      <el-input v-model="similarSearchData.signalLose[0]" placeholder="最小值" style="width: 80px;" />
                      <span>-</span>
                      <el-input v-model="similarSearchData.signalLose[1]" placeholder="最大值" style="width: 80px;" />
                    </div>
                  </el-form-item>
                </div>
              </div>
              <el-form-item>
                <el-button type="primary" :icon="Search" @click="() => handleSimilarSearch(1)">
                  查询
                </el-button>
                <el-button :icon="Refresh" @click="resetSimilarSearch">
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <div >
            <!-- 统计信息 Card (保持不变) -->
            <el-card shadow="never" class="flex-shrink-0 ">
              <div class="flex justify-between items-center">
                <span class="text-sm font-bold">统计信息</span>
              </div>
              <div class="grid grid-cols-4 ">
                <el-card shadow="hover" class="text-center">
                  <div class="text-2xl font-bold text-blue-600">
                    {{ chartStore.similarMatchesStatistics?.total_matches || 0 }}
                  </div>
                  <div class="text-sm text-gray-600">总比赛场次</div>
                </el-card>
                <el-card shadow="hover" class="text-center">
                  <el-progress
                    type="dashboard"
                    :percentage="chartStore.similarMatchesStatistics?.home_win_rate || 0"
                    :width="100"
                    
                    :format="() => `${chartStore.similarMatchesStatistics?.home_win_rate || 0}%`"
                  />
                  <div class="text-sm text-gray-600">主胜占比</div>
                </el-card>
                <el-card shadow="hover" class="text-center">
                  <el-progress
                    type="dashboard"
                    :percentage="chartStore.similarMatchesStatistics?.draw_rate || 0"
                    :width="100"                    
                    :format="() => `${chartStore.similarMatchesStatistics?.draw_rate || 0}%`"
                  />
                  <div class="text-sm text-gray-600 ">平局占比</div>
                </el-card>
                <el-card shadow="hover" class="text-center">
                  <el-progress
                    type="dashboard"
                    :percentage="chartStore.similarMatchesStatistics?.away_win_rate || 0"
                    :width="100"
                    
                    :format="() => `${chartStore.similarMatchesStatistics?.away_win_rate || 0}%`"
                  />
                  <div class="text-sm text-gray-600">客胜占比</div>
                </el-card>
              </div>
            </el-card>
          </div>
        </div>
      </el-card>

      <!-- 表格与分页 Card -->
     
        <!-- 表格区域容器 -->
        <div class="flex-1 overflow-auto flex flex-col "> <!-- 添加 flex flex-col 和 overflow-hidden -->
          <el-table
            :data="chartStore.similarMatches"
         
            @expand-change="handleSimilarMatchDetail"
            class="w-full flex-1"
            :fit="true"
          
          >
            <!-- 表格列定义 (保持不变) -->
            <el-table-column prop="event_name" label="赛事名称" width="120" fixed="left" />
            <el-table-column prop="order_num" label="赛事编号" width="50"  />
            <el-table-column prop="matchtime" label="比赛时间" width="160">
              <template #default="scope">
                {{ scope.row.matchtime ? new Date(scope.row.matchtime).toLocaleString() : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="homesxname" label="主队" width="120" />
            <el-table-column prop="awaysxname" label="客队" width="120" />
            <el-table-column prop="homescore" label="比分" width="80">
              <template #default="scope">
                {{ scope.row.homescore }}-{{ scope.row.awayscore }}
              </template>
            </el-table-column>
            <el-table-column label="初赔" width="200">
              <template #default="scope">
                <div class="flex  gap-1 text-xs">
                  <div>胜: {{ scope.row.home_initial?.toFixed(2) || '-' }}</div>
                  <div>平: {{ scope.row.draw_initial?.toFixed(2) || '-' }}</div>
                  <div>负: {{ scope.row.away_initial?.toFixed(2) || '-' }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="初赔信号" width="200">
              <template #default="scope">
                <div class="flex  gap-1 text-xs">
                  <span>胜: {{ scope.row.signal_home_initial?.toFixed(4) || '-' }}</span>
                  <span>平: {{ scope.row.signal_draw_initial?.toFixed(4) || '-' }}</span>
                  <span>负: {{ scope.row.signal_away_initial?.toFixed(4) || '-' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column type="expand" >
              <template #default="scope" class="min-h-[700px]">
                <div
                  v-if="expandedRows.has(scope.row.fid!)"
                  class="flex-1 "
                >
               
                  <MatchDetail 
                    :isLoadingSignals="chartStore.isLoadingSimilarMatchSignals"
                    :leftTableData="getMatchChartData(scope.row.fid!)?.leftTableData || []"
                    :rightTableData="getMatchChartData(scope.row.fid!)?.rightTableData || []"
                    :chartData293="getMatchChartData(scope.row.fid!)?.similarMatchChartData293 || { xData: [], seriesData: [] }"
                    :chartData18="getMatchChartData(scope.row.fid!)?.similarMatchChartData18 || { xData: [], seriesData: [] }"
                    :chartDataCombinedHome="getMatchChartData(scope.row.fid!)?.similarMatchChartDataCombinedHome || { xData: [], seriesData: [] }"
                    :chartDataCombinedDraw="getMatchChartData(scope.row.fid!)?.similarMatchChartDataCombinedDraw || { xData: [], seriesData: [] }"
                    :chartDataCombinedAway="getMatchChartData(scope.row.fid!)?.similarMatchChartDataCombinedAway || { xData: [], seriesData: [] }"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页信息区域 -->
        <!-- 确保这个容器是 flex-shrink-0 并且有明确的尺寸 -->
        <div
          v-if="chartStore.similarMatchesPagination.total > 0"
          class="pagination-container flex items-center justify-between px-4 py-2 border-t border-gray-200 flex-shrink-0"
          style="height: auto;" 
        >
          <span class="text-sm text-gray-600">
            共 {{ chartStore.similarMatchesPagination.total }} 条记录，
            第 {{ chartStore.similarMatchesPagination.current_page }} / {{ chartStore.similarMatchesPagination.total_pages }} 页
          </span>
          <el-pagination
            v-model:current-page="chartStore.similarMatchesPagination.current_page"
            :page-size="chartStore.similarMatchesPagination.page_size"
            :total="chartStore.similarMatchesPagination.total"
            :background="true"
            layout="prev, pager, next, jumper"
            @current-change="handlePageChange"
            class="ml-4" 
          />
        </div>
      
   
  </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
:deep(.echarts-for-vue) {
  width: 100%;
  height: 100%;
}

/* 修复Element Plus tabs的滚动问题 */
:deep(.el-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-tabs__content) {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

:deep(.el-tab-pane) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 表格样式修复 */
:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table__body-wrapper),
:deep(.el-table__header-wrapper) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

/* 确保表格列对齐 */
:deep(.el-table th),
:deep(.el-table td) {
  padding: 8px 0;
}

/* 展开行内容样式 */
:deep(.expandable-content) {
  max-height: 60vh;
  overflow-y: auto;
  overflow-x: hidden;
}

/* 分页样式修复 */
:deep(.el-pagination) {
  margin-top: 0;
}

/* 表格滚动区域修复 */
:deep(.el-table .el-table__body-wrapper) {
  overflow-x: auto;
}

/* 确保表格内容不换行 */
:deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>

<style>
.league-select-popper {
  width: fit-content !important;
  min-width: var(--el-select-input-width);
}

/* 全局表格样式修复 */
.el-table {
  table-layout: fixed;
}

.el-table__body,
.el-table__header {
  width: 100% !important;
}
</style>
